package com.originskyseed.platform.course.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.originskyseed.platform.core.aspect.annotation.RequiredParams;
import com.originskyseed.platform.core.base.BaseController;
import com.originskyseed.platform.core.base.BaseLocaleResource;
import com.originskyseed.platform.core.base.BasePage;
import com.originskyseed.platform.core.base.BaseResponseBody;
import com.originskyseed.platform.core.common.code.CommonResponseCode;
import com.originskyseed.platform.core.filter.helper.SingleSignOnTokenHelper;
import com.originskyseed.platform.course.i18n.CourseResponseMsg;
import com.originskyseed.platform.course.model.Paper;
import com.originskyseed.platform.course.model.PaperRelateAnswer;
import com.originskyseed.platform.course.model.PaperRelateSubject;
import com.originskyseed.platform.course.model.PaperRelateUser;
import com.originskyseed.platform.course.service.IPaperRelateAnswerService;
import com.originskyseed.platform.course.service.IPaperRelateUserService;
import com.originskyseed.platform.course.service.IPaperService;
import com.originskyseed.platform.course.vo.request.PaperRelateUserRequestVO;
import com.originskyseed.platform.task.model.Task;
import com.originskyseed.platform.task.model.TaskRelateAssignPerson;
import com.originskyseed.platform.task.service.ITaskRelateAssignPersonService;
import com.originskyseed.platform.task.service.ITaskService;
import com.originskyseed.platform.user.model.UserInfo;

/**
 * 试卷关联作答用户信息Controller类（OSI_PAPER_RELATE_USER）
 *
 * @author Tangwanghui
 */
@Controller
@RequestMapping("/paperRelateUser")
@BaseLocaleResource(localeFileName = "i18n_course")
public class PaperRelateUserController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(PaperRelateUserController.class);

	@DubboReference
	private IPaperRelateUserService paperRelateUserService;

	@DubboReference
	private IPaperRelateAnswerService paperRelateAnswerService;

	@DubboReference
	private IPaperService paperService;

	@DubboReference
	private ITaskRelateAssignPersonService taskRelateAssignPersonService;

	@DubboReference
	private ITaskService taskService;

	/**
	 * 分页查询
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/paperRelateUserList.json", method = RequestMethod.POST)
	@RequiredParams(names = { "pageNo", "pageSize" })
	public BaseResponseBody<BasePage<PaperRelateUser>> paperRelateUserList(HttpServletRequest request) {
		BaseResponseBody<BasePage<PaperRelateUser>> result = null;
		try {
			// 请求对象
			PaperRelateUserRequestVO requestVO = this.getParameterBean(PaperRelateUserRequestVO.class);

			// 分页查询
			BasePage<PaperRelateUser> page = new BasePage<PaperRelateUser>(requestVO.getPageNo(), requestVO.getPageSize());
			page = this.paperRelateUserService.selectListByPage(requestVO.toMap(), page);
			result = new BaseResponseBody<BasePage<PaperRelateUser>>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.DATA_SUCCESS.getMsg()), page);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<BasePage<PaperRelateUser>>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.DATA_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 分页查询
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/paperRelateUserListByUserId.json", method = RequestMethod.POST)
	@RequiredParams(names = { "pageNo", "pageSize" })
	public BaseResponseBody<BasePage<PaperRelateUser>> paperRelateUserListByUserId(HttpServletRequest request) {
		BaseResponseBody<BasePage<PaperRelateUser>> result = null;
		try {
			// 请求对象
			PaperRelateUserRequestVO requestVO = this.getParameterBean(PaperRelateUserRequestVO.class);
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			requestVO.setCreatorId(userInfo == null ? "" : userInfo.getId());
			// 分页查询
			BasePage<PaperRelateUser> page = new BasePage<PaperRelateUser>(requestVO.getPageNo(), requestVO.getPageSize());
			page = this.paperRelateUserService.selectListByPage(requestVO.toMap(), page);
			result = new BaseResponseBody<BasePage<PaperRelateUser>>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.DATA_SUCCESS.getMsg()), page);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<BasePage<PaperRelateUser>>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.DATA_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 任务广场 查询已考试的用户
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/gradeSelectPaperUserList.json", method = RequestMethod.POST)
	@RequiredParams(names = { "pageNo", "pageSize", "taskId" })
	public BaseResponseBody<BasePage<PaperRelateUser>> gradeSelectPaperUserList(HttpServletRequest request) {
		BaseResponseBody<BasePage<PaperRelateUser>> result = null;
		try {
			// 请求对象
			PaperRelateUserRequestVO requestVO = this.getParameterBean(PaperRelateUserRequestVO.class);
			String taskId = this.getParameterString("taskId", null);
			requestVO.setTaskId(taskId);
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			// 分页查询
			// 任务创建人可以看到所有考卷，作答人只能看到自己的考卷
			BasePage<PaperRelateUser> page = new BasePage<PaperRelateUser>(requestVO.getPageNo(), requestVO.getPageSize());

			Task task = taskService.selectByPrimaryKey(taskId);
			int isOwnAnswer = 0;// 标识是作答还是评卷 0是作答 1是评卷
			if (task != null) {
				if (task.getCreatorId().equals(userInfo.getId())) {
					page = this.paperRelateUserService.gradeSelectPaperListByPage(requestVO.toMap(), page, taskId);
					isOwnAnswer = 1;
				} else {
					requestVO.setCreatorId(userInfo.getId());
					page = this.paperRelateUserService.gradeSelectPaperListByPage(requestVO.toMap(), page, taskId);
				}
				List<PaperRelateUser> list = page.getResults();
				if (list != null && list.size() > 0) {
					for (int i = 0; i < list.size(); i++) {
						PaperRelateUser paperRelateUser = list.get(i);

						if (paperRelateUser.getIsGrade() == 1)// 已经评卷后，就不能再次评卷
						{
							isOwnAnswer = 0;
						}
						paperRelateUser.setIsOwnAnswer(isOwnAnswer);
					}
				}
			}
			result = new BaseResponseBody<BasePage<PaperRelateUser>>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.DATA_SUCCESS.getMsg()), page);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<BasePage<PaperRelateUser>>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.DATA_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 保存信息_考试作答记录
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/paperRelateUserAnswerSave.json", method = RequestMethod.POST)
	@RequiredParams(names = {})
	public BaseResponseBody<PaperRelateUser> paperRelateUserAnswerSave(HttpServletRequest request) {
		BaseResponseBody<PaperRelateUser> result = null;
		try {
			// 请求对象
			PaperRelateUser paperRelateUser = this.getParameterBean(PaperRelateUser.class);
			Paper paper = this.getParameterBean(Paper.class);
			List<PaperRelateAnswer> paperRelateAnswerList = this.getParameterList("paperRelateAnswerList", PaperRelateAnswer.class);
			List<PaperRelateSubject> paperRelateSubjectList = this.getParameterList("paperRelateSubjectList", PaperRelateSubject.class);// 题目
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			// 查询用户考卷关联
			PaperRelateUser relateUser = new PaperRelateUser();
			relateUser.setCreatorId(paperRelateUser.getCreatorId());
			relateUser.setPaperId(paperRelateUser.getPaperId());
			relateUser.setTaskId(paperRelateUser.getTaskId());
			PaperRelateUser isExam = this.paperRelateUserService.selectRelateUserIsExam(relateUser);
			// 查询是否存在
			if (isExam != null && StringUtils.isNotBlank(isExam.getId())) { // 评分
				// 更改任务状态
				TaskRelateAssignPerson taskRelateAssignPerson = this.taskRelateAssignPersonService.selectPaperIsMyTask(paperRelateUser.getTaskId(), paperRelateUser.getCreatorId());
				if (taskRelateAssignPerson != null) {
					paperRelateUser.setId(isExam.getId());
					// 查询及格分
					Paper paper1 = this.paperService.selectByPrimaryKey(paperRelateUser.getPaperId());
					// 大小比较
					int flag = paperRelateUser.getScore().compareTo(paper1.getPassingScore());
					if (flag > 0 || flag == 0) { // 及格
						paperRelateUser.setState(2);// 通过
						taskRelateAssignPerson.setState(2);// 完成
						taskRelateAssignPerson.setFinishTime(new Date());
					} else {
						paperRelateUser.setState(3);// 未通过
						taskRelateAssignPerson.setState(1);// 未完成
					}
					this.taskRelateAssignPersonService.updateByPrimaryKeySelective(taskRelateAssignPerson);
					this.paperRelateUserService.updateByPrimaryKeySelective(paperRelateUser);
					return new BaseResponseBody<PaperRelateUser>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.PAPER_SAVE_GRADE_SUCCESS.getMsg()), paperRelateUser);
				}
			} else {
				this.paperRelateUserService.insertPaperAnswer(paperRelateUser, paperRelateAnswerList, userInfo, paper, paperRelateSubjectList);
			}
			result = new BaseResponseBody<PaperRelateUser>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.PAPER_SAVE_SUCCESS.getMsg()), paperRelateUser);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<PaperRelateUser>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.PAPER_SAVE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 提交考卷待评分
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/paperRelateUserGrade.json", method = RequestMethod.POST)
	@RequiredParams(names = {})
	public BaseResponseBody<PaperRelateUser> paperRelateUserGrade(HttpServletRequest request) {
		BaseResponseBody<PaperRelateUser> result = null;
		try {
			// 请求对象
			PaperRelateUser paperRelateUser = this.getParameterBean(PaperRelateUser.class);
			Integer isOwnAnswer = paperRelateUser.getIsOwnAnswer();
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			List<PaperRelateAnswer> paperRelateAnswerList = this.getParameterList("paperRelateAnswerList", PaperRelateAnswer.class);
			List<PaperRelateSubject> paperRelateSubjectList = this.getParameterList("paperRelateSubjectList", PaperRelateSubject.class);// 题目

			if (isOwnAnswer == 0)// 0是作答
			{
				Paper paper = this.getParameterBean(Paper.class);
				this.paperRelateUserService.insertPaperAnswer(paperRelateUser, paperRelateAnswerList, userInfo, paper, paperRelateSubjectList);
			} else if (isOwnAnswer == 1)// 评卷
			{
				TaskRelateAssignPerson taskRelateAssignPerson = this.taskRelateAssignPersonService.selectPaperIsMyTask(paperRelateUser.getTaskId(), paperRelateUser.getCreatorId());
				if (taskRelateAssignPerson != null) {
					// 查询及格分
					Paper paper = this.paperService.selectByPrimaryKey(paperRelateUser.getPaperId());
					// 大小比较
					int flag = paperRelateUser.getScore().compareTo(paper.getPassingScore());
					if (flag > 0 || flag == 0) { // 及格
						paperRelateUser.setState(2);// 通过
						taskRelateAssignPerson.setState(2);// 完成
						taskRelateAssignPerson.setFinishTime(new Date());
					} else {
						paperRelateUser.setState(3);// 未通过
						taskRelateAssignPerson.setState(1);// 未完成
					}
					this.taskRelateAssignPersonService.updateByPrimaryKeySelective(taskRelateAssignPerson);
				}
				paperRelateUser.setIsGrade(1);
				paperRelateUser.setGradeId(userInfo.getId());
				paperRelateUser.setGradeName(userInfo.getName());
				this.paperRelateUserService.updateByPrimaryKeySelective(paperRelateUser);
			}
			return new BaseResponseBody<PaperRelateUser>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.PAPER_SAVE_GRADE_SUCCESS.getMsg()), paperRelateUser);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<PaperRelateUser>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.PAPER_SAVE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 评分（停用）
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/paperRelateUserSave.json", method = RequestMethod.POST)
	@RequiredParams(names = { "paperId", "creatorId", "taskId", "score" })
	public BaseResponseBody<PaperRelateUser> paperRelateUserSave(HttpServletRequest request) {
		BaseResponseBody<PaperRelateUser> result = null;
		try {
			// 请求对象
			PaperRelateUser paperRelateUser = this.getParameterBean(PaperRelateUser.class);
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			PaperRelateUser relateUser = this.paperRelateUserService.selectByPaperRelateUser(paperRelateUser);
			if (relateUser != null) {
				paperRelateUser.setId(relateUser.getId());
			}
			if (StringUtils.isNotBlank(paperRelateUser.getId())) {
				// 更改任务状态
				TaskRelateAssignPerson taskRelateAssignPerson = new TaskRelateAssignPerson();
				taskRelateAssignPerson.setTaskId(paperRelateUser.getTaskId());
				taskRelateAssignPerson.setUserId(paperRelateUser.getCreatorId());
				taskRelateAssignPerson.setIsDel(0);
				TaskRelateAssignPerson assignPerson = this.taskRelateAssignPersonService.selectByTaskTaskRelateAssignPerson(taskRelateAssignPerson);
				if (assignPerson != null) {
					taskRelateAssignPerson.setId(assignPerson.getId());
					// 查询及格分
					Paper paper = this.paperService.selectByPrimaryKey(paperRelateUser.getPaperId());
					// 大小比较
					int flag = paperRelateUser.getScore().compareTo(paper.getPassingScore());
					if (flag > 0 || flag == 0) { // 及格
						paperRelateUser.setState(2);// 通过
						taskRelateAssignPerson.setState(2);// 完成
						this.taskRelateAssignPersonService.updateByPrimaryKeySelective(taskRelateAssignPerson);
					} else {
						paperRelateUser.setState(3);// 未通过
					}
					this.paperRelateUserService.updateByPrimaryKeySelective(paperRelateUser);
				}
			}
			result = new BaseResponseBody<PaperRelateUser>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.SAVE_SUCCESS.getMsg()), paperRelateUser);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<PaperRelateUser>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.SAVE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 删除信息
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/paperRelateUserDelete.json", method = RequestMethod.POST)
	@RequiredParams(names = { "ids" })
	public BaseResponseBody<Boolean> paperRelateUserDelete(HttpServletRequest request) {
		BaseResponseBody<Boolean> result = null;
		try {
			// 请求参数
			String[] ids = this.getParameterArray("ids", new String[] {});

			this.paperRelateUserService.deleteByPrimaryKeys(Arrays.asList(ids));
			result = new BaseResponseBody<Boolean>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.DELETE_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<Boolean>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.DELETE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

}
